﻿using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Web;
using Hematology.Data;
using Hematology.Tools;
using NgoResource = Hematology.UserSite.App_GlobalResources.UserSite;

namespace Hematology.UserSite
{
	public partial class Search : System.Web.UI.Page
	{
		protected string SearchPhrase
		{
			get { return ViewState["SearchPhrase"] != null ? ViewState["SearchPhrase"].ToString() : String.Empty; }
			set { ViewState["SearchPhrase"] = value; }
		}

		protected void Page_Load(object sender, EventArgs e)
		{
			if (Page.IsPostBack)
				return;

			string searchPhrase = Request.QueryString["key"];
			if (String.IsNullOrEmpty(searchPhrase))
				return;

			SearchPhrase = HttpUtility.UrlDecode(searchPhrase);

			List<SiteContent> lAllContent = SiteContent.ListAllContent(null, true, false);
			if (lAllContent != null)
			{
				lAllContent.RemoveAll(siteContent => !PageHelper.RemoveHtmlTags(siteContent.Content).ToLower().Contains(SearchPhrase.ToLower()));

				foreach (SiteContent siteContent in lAllContent)
				{
					siteContent.Teaser = PageHelper.GetSearchTeaser(siteContent, searchPhrase);
				}
			}

			rptSiteContent.DataSource = lAllContent;
			rptSiteContent.DataBind();
		}

		protected string GetExtendedSearchResultTitle(object oTitle, object oContent, object oTargetPage, object oSiteContentId)
		{
			int iMatchCount = new Regex(SearchPhrase).Matches(oContent.ToString()).Count;
			string sTargetUrl = String.Format(oTargetPage.ToString(), Request.Url.Host, oSiteContentId);

			return String.Format("<a href={0}>{1}</a> <span class=\"note\">[{2}: {3}]</span>", sTargetUrl, oTitle, NgoResource.resMatches, iMatchCount);
		}
	}
}